/**
 * 工具函数库
 * 提供常用的工具函数和辅助方法
 */

// 工具函数对象
const Utils = {
    /**
     * 显示加载动画
     */
    showLoading() {
        const loading = document.getElementById('loading');
        if (loading) {
            loading.classList.add('active');
        }
    },

    /**
     * 隐藏加载动画
     */
    hideLoading() {
        const loading = document.getElementById('loading');
        if (loading) {
            loading.classList.remove('active');
        }
    },

    /**
     * 显示消息提示
     * @param {string} message - 消息内容
     * @param {string} type - 消息类型: success, error, warning, info
     * @param {number} duration - 显示时长(毫秒)
     */
    showToast(message, type = 'info', duration = 3000) {
        const toast = document.getElementById('toast');
        if (!toast) return;

        // 清除之前的类
        toast.className = 'toast';
        
        // 设置消息内容和类型
        toast.textContent = message;
        toast.classList.add(type);
        toast.classList.add('show');

        // 自动隐藏
        setTimeout(() => {
            toast.classList.remove('show');
        }, duration);
    },

    /**
     * 显示模态框
     * @param {string} title - 标题
     * @param {string} content - 内容HTML
     * @param {Function} onClose - 关闭回调
     */
    showModal(title, content, onClose = null) {
        const modal = document.getElementById('modal-overlay');
        const modalTitle = document.getElementById('modal-title');
        const modalBody = document.getElementById('modal-body');
        
        if (!modal || !modalTitle || !modalBody) return;

        modalTitle.textContent = title;
        modalBody.innerHTML = content;
        modal.classList.add('active');

        // 绑定关闭事件
        const closeModal = () => {
            modal.classList.remove('active');
            if (onClose) onClose();
        };

        // 点击遮罩层关闭
        modal.addEventListener('click', (e) => {
            if (e.target === modal) {
                closeModal();
            }
        });

        // ESC键关闭
        const handleEsc = (e) => {
            if (e.key === 'Escape') {
                closeModal();
                document.removeEventListener('keydown', handleEsc);
            }
        };
        document.addEventListener('keydown', handleEsc);

        // 关闭按钮
        const closeBtn = document.getElementById('modal-close');
        if (closeBtn) {
            closeBtn.onclick = closeModal;
        }
    },

    /**
     * 隐藏模态框
     */
    hideModal() {
        const modal = document.getElementById('modal-overlay');
        if (modal) {
            modal.classList.remove('active');
        }
    },

    /**
     * 格式化日期
     * @param {Date|string} date - 日期
     * @param {string} format - 格式
     */
    formatDate(date, format = 'YYYY-MM-DD HH:mm:ss') {
        if (!date) return '';
        
        const d = new Date(date);
        if (isNaN(d.getTime())) return '';

        const year = d.getFullYear();
        const month = String(d.getMonth() + 1).padStart(2, '0');
        const day = String(d.getDate()).padStart(2, '0');
        const hours = String(d.getHours()).padStart(2, '0');
        const minutes = String(d.getMinutes()).padStart(2, '0');
        const seconds = String(d.getSeconds()).padStart(2, '0');

        return format
            .replace('YYYY', year)
            .replace('MM', month)
            .replace('DD', day)
            .replace('HH', hours)
            .replace('mm', minutes)
            .replace('ss', seconds);
    },

    /**
     * 防抖函数
     * @param {Function} func - 要防抖的函数
     * @param {number} wait - 等待时间
     */
    debounce(func, wait) {
        let timeout;
        return function executedFunction(...args) {
            const later = () => {
                clearTimeout(timeout);
                func(...args);
            };
            clearTimeout(timeout);
            timeout = setTimeout(later, wait);
        };
    },

    /**
     * 节流函数
     * @param {Function} func - 要节流的函数
     * @param {number} limit - 时间限制
     */
    throttle(func, limit) {
        let inThrottle;
        return function(...args) {
            if (!inThrottle) {
                func.apply(this, args);
                inThrottle = true;
                setTimeout(() => inThrottle = false, limit);
            }
        };
    },

    /**
     * 深拷贝对象
     * @param {any} obj - 要拷贝的对象
     */
    deepClone(obj) {
        if (obj === null || typeof obj !== 'object') return obj;
        if (obj instanceof Date) return new Date(obj.getTime());
        if (obj instanceof Array) return obj.map(item => this.deepClone(item));
        if (typeof obj === 'object') {
            const clonedObj = {};
            for (const key in obj) {
                if (obj.hasOwnProperty(key)) {
                    clonedObj[key] = this.deepClone(obj[key]);
                }
            }
            return clonedObj;
        }
    },

    /**
     * 生成唯一ID
     */
    generateId() {
        return Date.now().toString(36) + Math.random().toString(36).substr(2);
    },

    /**
     * 验证邮箱格式
     * @param {string} email - 邮箱地址
     */
    isValidEmail(email) {
        const emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
        return emailRegex.test(email);
    },

    /**
     * 验证手机号格式
     * @param {string} phone - 手机号
     */
    isValidPhone(phone) {
        const phoneRegex = /^1[3-9]\d{9}$/;
        return phoneRegex.test(phone);
    },

    /**
     * 获取URL参数
     * @param {string} name - 参数名
     */
    getUrlParam(name) {
        const urlParams = new URLSearchParams(window.location.search);
        return urlParams.get(name);
    },

    /**
     * 设置URL参数
     * @param {string} name - 参数名
     * @param {string} value - 参数值
     */
    setUrlParam(name, value) {
        const url = new URL(window.location);
        url.searchParams.set(name, value);
        window.history.replaceState({}, '', url);
    },

    /**
     * 复制文本到剪贴板
     * @param {string} text - 要复制的文本
     */
    async copyToClipboard(text) {
        try {
            await navigator.clipboard.writeText(text);
            this.showToast('已复制到剪贴板', 'success');
        } catch (err) {
            // 降级方案
            const textArea = document.createElement('textarea');
            textArea.value = text;
            document.body.appendChild(textArea);
            textArea.select();
            document.execCommand('copy');
            document.body.removeChild(textArea);
            this.showToast('已复制到剪贴板', 'success');
        }
    },

    /**
     * 下载文件
     * @param {string} content - 文件内容
     * @param {string} filename - 文件名
     * @param {string} type - MIME类型
     */
    downloadFile(content, filename, type = 'text/plain') {
        const blob = new Blob([content], { type });
        const url = URL.createObjectURL(blob);
        const a = document.createElement('a');
        a.href = url;
        a.download = filename;
        document.body.appendChild(a);
        a.click();
        document.body.removeChild(a);
        URL.revokeObjectURL(url);
    },

    /**
     * 格式化文件大小
     * @param {number} bytes - 字节数
     */
    formatFileSize(bytes) {
        if (bytes === 0) return '0 Bytes';
        const k = 1024;
        const sizes = ['Bytes', 'KB', 'MB', 'GB', 'TB'];
        const i = Math.floor(Math.log(bytes) / Math.log(k));
        return parseFloat((bytes / Math.pow(k, i)).toFixed(2)) + ' ' + sizes[i];
    },

    /**
     * 获取状态标签HTML
     * @param {string} status - 状态值
     * @param {string} type - 状态类型
     */
    getStatusBadge(status, type = 'default') {
        const statusMap = {
            '待审核': { class: 'status-pending', text: '待审核' },
            '审核通过': { class: 'status-approved', text: '审核通过' },
            '审核未通过': { class: 'status-rejected', text: '审核未通过' },
            '启用': { class: 'status-active', text: '启用' },
            '禁用': { class: 'status-inactive', text: '禁用' },
            '1': { class: 'status-active', text: '启用' },
            '0': { class: 'status-inactive', text: '禁用' }
        };

        const statusInfo = statusMap[status] || { class: 'status-inactive', text: status };
        return `<span class="status-badge ${statusInfo.class}">${statusInfo.text}</span>`;
    },

    /**
     * 清空表单
     * @param {string|HTMLElement} form - 表单选择器或元素
     */
    clearForm(form) {
        const formElement = typeof form === 'string' ? document.querySelector(form) : form;
        if (formElement) {
            formElement.reset();
        }
    },

    /**
     * 获取表单数据
     * @param {string|HTMLElement} form - 表单选择器或元素
     */
    getFormData(form) {
        const formElement = typeof form === 'string' ? document.querySelector(form) : form;
        if (!formElement) return {};

        const formData = new FormData(formElement);
        const data = {};
        for (const [key, value] of formData.entries()) {
            data[key] = value;
        }
        return data;
    },

    /**
     * 设置表单数据
     * @param {string|HTMLElement} form - 表单选择器或元素
     * @param {Object} data - 数据对象
     */
    setFormData(form, data) {
        const formElement = typeof form === 'string' ? document.querySelector(form) : form;
        if (!formElement) return;

        Object.keys(data).forEach(key => {
            const input = formElement.querySelector(`[name="${key}"]`);
            if (input) {
                input.value = data[key];
            }
        });
    },

    /**
     * 滚动到元素
     * @param {string|HTMLElement} element - 元素选择器或元素
     * @param {Object} options - 滚动选项
     */
    scrollToElement(element, options = {}) {
        const targetElement = typeof element === 'string' ? document.querySelector(element) : element;
        if (targetElement) {
            targetElement.scrollIntoView({
                behavior: 'smooth',
                block: 'start',
                ...options
            });
        }
    },

    /**
     * 检查元素是否在视口中
     * @param {HTMLElement} element - 元素
     */
    isInViewport(element) {
        const rect = element.getBoundingClientRect();
        return (
            rect.top >= 0 &&
            rect.left >= 0 &&
            rect.bottom <= (window.innerHeight || document.documentElement.clientHeight) &&
            rect.right <= (window.innerWidth || document.documentElement.clientWidth)
        );
    }
};

// 导出工具函数
window.Utils = Utils;

